#include "Geometry.h"

//Sphere

//Default constructor
Sphere::Sphere()
{
	center = Vector3(0.0f, 0.0f, 0.0f);
	radius = 0.0f;
}

//Initialization
Sphere::Sphere(const Vector3& c, float r)
{
	center = c;
	radius = r;
}

bool Sphere::IntersectionTest(Ray3& ray, float tmin, float tmax, IntersectionPacket& pkt)
{
	float A,B,C;		//the three components of the quadratic equation
	float discriminant;
	float t1, t2;
	
	//calculate A,B,C
	//We don't assume the ray to be of unit length
	A = ray.direction * ray.direction;		//d.d
	B = ray.direction * (ray.origin - center);
	C = ((ray.origin - center) * (ray.origin - center)) - (radius * radius);

	//calculate discriminant
	discriminant = (B*B - A*C);
	if(discriminant < 0)
	{
		//imaginary roots
		return false;
	}
	
	t1 = (-B - sqrtf(discriminant))/A;
	t2 = (-B + sqrtf(discriminant))/A;
		
	//get minimal t
	// equated to 0.0f because we have to prevent self intersection in case of secondary rays with same object
	// and we dont need negative values because we are interested only in the positive half of ray
	// tmin and tmax we will use later
	if(t1 <= 0.0f && t2 <= 0.0f) return false;		
	else if(t1 <= 0.0f && t2 > 0.0f) { pkt.t = t2; return true; }
	else if(t2 <= 0.0f && t1 > 0.0f) { pkt.t = t1; return true; }
	//both positive side
	//return the least of both t1 and t2
	else if(t1 > 0.0f && t2 > 0.0f) { pkt.t = (t1 <= t2)?t1:t2; return true; }
	
	//end of intersection test for sphere
}

//Intersection between shadow ray and sphere
bool Sphere::ShadowRayTest(Ray3& ray, float tmin, float tmax)
{
	float A,B,C;		//the three components of the quadratic equation
	float discriminant;
	float t1, t2;
	
	//calculate A,B,C
	//We don't assume the ray to be of unit length
	A = ray.direction * ray.direction;		//d.d
	B = ray.direction * (ray.origin - center);
	C = ((ray.origin - center) * (ray.origin - center)) - (radius * radius);

	//calculate discriminant
	discriminant = (B*B - A*C);
	if(discriminant < 0)
	{
		//imaginary roots
		return false;
	}
	
	t1 = (-B - sqrtf(discriminant))/A;
	t2 = (-B + sqrtf(discriminant))/A;
	
	if(t1 <= 0.0f && t2 <= 0.0f) return false;
	else if(t1 <= 0.0f && t2 > 0.0f) return true;
	else if(t2 <= 0.0f && t2 > 0.0f) return true;
	else if(t1 > 0.0f && t2 > 0.0f) return true;	// both positive
	
	//end of shadow ray intersection test for sphere
}



